<template>
  <div v-if="examData.id">
    <exam-info-view-m :timeCount="timeCount" @sendTipCardClick="tipCardClick"
                      @sendSubmitClick="submitClick"></exam-info-view-m>
    <exam-question-m v-model="selectedIndex" :question-list="examData.questions" :answer-data="answerData"
                     :exam-type="examData.examType" @sendAnswerClick="answerClick"
                     @sendSubmitClick="submitClick"></exam-question-m>


    <van-popup v-model="showTipCover" position="bottom">
      <tip-card-m v-model="selectedIndex" :question-list="examData.questions" :answer-data="answerData"
                  @sendCloseTipCard="closeTipCard"></tip-card-m>
    </van-popup>

  </div>
</template>

<script>

  import TipCardM from '../components/TipCardM'
  import ExamQuestionM from '../components/ExamQuestionM'
  import ExamInfoViewM from '../components/ExamInfoViewM'
  import ExamTool from '../ExamTool'

  import {Dialog, Popup, Toast} from 'vant'

  Vue.use(Dialog)
  Vue.use(Popup)

  export default {
    name: 'overall-m',
    //examType 1:统筹考试 2:普通考试 3:模拟考试 4:题库练习
    data() {
      return {
        examId: this.$route.params.examId,
        subjectId: this.$route.params.subjectId || 0,
        type: this.$route.params.type || 0,
        showTipCover: false,
        timer: null,
        timeCount: 10000,
        selectedIndex: 0,
        answerData: {},
        examData: {},
        completed: false,
        examResultId: 0,
      }
    },
    components: {
      TipCardM,
      ExamQuestionM,
      ExamInfoViewM
    },
    computed: {},
    created() {

      // if (window.name == "") {
      //   console.log("首次被加载");
      //
      // }
      //   history.pushState(null, null, document.URL);
      // } else if (window.name == "isReload") {
      //   console.log("页面被刷新");
      // };
      // setTimeout(() => {
      //   window.onpopstate = this.popstate;
      //   console.log('首次被加载created', history)
      //
      // }, 1000)
    },
    beforeDestroy() {
      this.clearTimer()
      window.onpopstate = () => {
      };
      window.name = ""
    },
    mounted() {
      if (this.type == 1) {
        ExamTool.checkCanExam(this.subjectId, this.examId).then((result) => {
          let data = result.responseData
          if (data.canExam == 1) {
            this.loadExamDetail()
          }
        })
      } else if (this.type == 2) {
        ExamTool.checkCanExamPlan(this.subjectId).then((result) => {
          let planInfo = result.responseData
          if (planInfo.overallExamIds && planInfo.overallExamIds[0] == this.examId) {
            if (ExamTool.checkHasBuyPlan(planInfo)){
              if(planInfo.subjectPassStatus === 1){
                this.loadExamDetail()
              }else{
                Toast('您还有未通过的课程考试，请通过后再参加大考')
              }
            }else{
                Toast('未购买该课程包')
            }
          }else{
            Toast('非该课程的大考')
          }
        })
      }
    },

    methods: {

      //返回页面时监听
      popstate(e) {

        if (this.completed) {
          this.completed = false
          window.onpopstate = () => {
          };
          if (this.examData.examType == 4) {
            //练习模式
            this.$_router.replace(`/exam/result/practice/${this.subjectId}/${this.examId}/${this.examResultId}/0`)
          } else {
            this.$_router.replace(`/exam/result/general/${this.subjectId}/${this.examId}/${this.examResultId}/${this.type}`)
          }

        } else {

          history.pushState(null, null, document.URL);

          Dialog.confirm({
            title: '确认结束考试',
            message: '结束后则默认为交卷，请考生慎重选择。',
          })
            .then(() => {

              Toast.loading({
                duration: 0,
                message: '正在交卷',
                forbidClick: true,
              });

              if (this.type == 2) {
                ExamTool.submitExamPlan(this.examId, this.subjectId, this.answerData).then((result) => {

                  Toast.clear()
                  //清除缓存答案
                  ExamTool.removeExamAnswerCache()
                  let data = result.responseData

                  this.completed = true
                  this.examResultId = data.id
                  this.$router.go(-1)

                }).catch((err) => {

                  Toast.clear()
                })
              } else {


                ExamTool.submitExam(this.examId, this.subjectId, this.answerData).then((result) => {

                  Toast.clear()
                  //清除缓存答案
                  ExamTool.removeExamAnswerCache()
                  let data = result.responseData

                  this.completed = true
                  this.examResultId = data.id
                  this.$router.go(-1)

                }).catch((err) => {

                  Toast.clear()
                })
              }

            })
            .catch(() => {

            })

        }
      },

      loadExamDetail() {
        ExamTool.getExamDetail(this.examId, this.subjectId, this.type, (data) => {
          this.examData = data
          if (this.examData.examTimeLimit > 0) {
            this.timeCount = ExamTool.getOverTime(this.examData.startExamTimeLong, this.examData.examTimeLimit || 0)
            if (this.timeCount > 0) {
              this.startTimer()
            }
          } else {
            this.timeCount = 0
          }

          if (this.examData.examType == 1) {

            Dialog.alert({
              title: '确认考试',
              message: '请注意以下事项。\n' +
                '1、请保持设备稳定无异常。\n' +
                '2、请保持良好的网络环境。\n' +
                '3、中途退出则视为交卷。\n' +
                '4、超过考试时长则自动交卷',
              confirmButtonText: '我知道了'
            }).then(() => {
            })

          }

          if (window.name == "") {
            history.pushState(null, null, document.URL);
            window.name = "isReload";
          }
          window.onpopstate = this.popstate;

          if (this.examData.examType == 1 || this.examData.examType == 2 || this.examData.examType == 3) {
            //统筹考试或普通考试或模拟考试 获取缓存答案
            ExamTool.getExamAnswerCache().then((res) => {
              if (!res) {
                if (this.examData.examTimeLimit > 0 && this.timeCount <= 0) {
                  this.submitClick()
                }
                return
              }
              if (res.examId == this.examData.id) {
                //当拉取题目时发现已经超过考试时间自动交卷
                if (this.examData.examTimeLimit > 0 && this.timeCount <= 0) {
                  this.answerData = res.answerData
                  this.submitClick()
                } else if (ExamTool.nowInExamTime(res)) {
                  this.answerData = res.answerData
                  Dialog.alert({
                    title: '考试提示',
                    message: '您有未完成的考试，请继续考试。',
                    confirmButtonText: '继续考试'
                  }).then(() => {
                  })
                }
              } else {
                ExamTool.removeExamAnswerCache()
              }

            })

          }

          switch (this.examData.examType) {
            case 1:
              document.title = "统筹考试"
              break;
            case 2:
              document.title = "正式考试"

              break;
            case 3:
              document.title = "模拟考试"

              break;
            case 4:
              document.title = "题库练习"
              break;
            default:
              break;
          }

        })

      },
      answerClick() {
        let answerData = {...this.answerData}
        this.answerData = answerData

        if (this.examData.examType == 1 || this.examData.examType == 2 || this.examData.examType == 3) {
          //统筹考试或普通考试或模拟考试 缓存答案
          ExamTool.saveExamAnswerCache(this.examData, this.answerData).then((res) => {


          })

        }
      },
      //启用定时器
      startTimer() {
        this.timer = setInterval(() => {
          this.timeCount--

          if (this.timeCount === 0) {
            this.clearTimer()
            //考试结束，提交答案
            this.submitClick()
          }

        }, 1000)
      },
      //关闭定时器
      clearTimer() {
        clearInterval(this.timer)
      },
      //打开答题卡
      tipCardClick() {
        this.showTipCover = true
      },
      //关闭答题卡
      closeTipCard() {
        this.showTipCover = false
      },
      //答案提交
      submitClick() {

        Toast.loading({
          duration: 0,
          message: '正在交卷',
          forbidClick: true,
        });

        if (this.type == 2) {
          ExamTool.submitExamPlan(this.examId, this.subjectId, this.answerData).then((result) => {

            Toast.clear()
            //清除缓存答案
            ExamTool.removeExamAnswerCache()
            let data = result.responseData

            this.completed = true
            this.examResultId = data.id
            this.$router.go(-1)

          }).catch((err) => {

            Toast.clear()
          })
        } else {


          ExamTool.submitExam(this.examId, this.subjectId, this.answerData).then((result) => {

            Toast.clear()
            //清除缓存答案
            ExamTool.removeExamAnswerCache()
            let data = result.responseData

            this.completed = true
            this.examResultId = data.id
            this.$router.go(-1)

          }).catch((err) => {

            Toast.clear()
          })
        }
      }
    }
  }
</script>

<style scoped>

</style>
